#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import datetime
from functools import wraps
from flask import Module, Response, request, flash, jsonify, g, current_app,\
    abort, redirect, url_for, session, Blueprint, render_template

from planet.post import api
from planet.account.models import User, Profile
from planet.extensions import db, cache


def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth:
            message = {
            'status_code': 10001,
            'message': 'Login required',
            }
            resp = jsonify(message)
            return resp
        else:
            user, authenticated = User.query.authenticate(auth.username, auth.password)
            if not authenticated:
                message = {
                    'status_code': 10002,
                    'message': 'Authentication Failed',
                }
                resp = jsonify(message)
                return resp
        return f(*args, **kwargs)
    return decorated


@api.route("/account/verify_credentials", methods = ['GET'])
@requires_auth
def verify_credentials():
    # print request.headers
    account = request.authorization.username
    user = User.query.filter(db.or_(User.username==account, 
                                  User.email==account)).first()
    if not user.profile:
        profile = Profile()
        user.profile = profile

        db.session.add(user)
        db.session.commit()

    message = {
            'status_code' : 10000,
            'message' : 'success',
            'user' : {
                'id' : user.id, 
                'username' : user.username,
                'email': user.email,
                'phone': user.profile.phone or '',
            }
        }
    resp = jsonify(message)
    resp.mimetype='application/json'
    return resp


@api.route("/account/create", methods = ['POST'])
def create():
    if request.authorization:
        message = {
            'status_code' : 10003,
            'message': 'You have authentication',
        }
        resp = jsonify(message)
        return resp                

    email = request.values.get('email')
    username = request.values.get('username')
    password = request.values.get('password')
    password_confirm = request.values.get('password_confirm')

    if not email or not username or not password or not password_confirm:
        message = {
            'status_code' : 20001, 
            'message' : 'args is null',
        }
        resp = jsonify(message)
        return resp
    
    if password != password_confirm:
        message = {
            'status_code' : 20002,
            'message' : 'password does not matchrd'
        }
        resp = jsonify(message)
        return resp

    user = User.query.filter_by(email=email).first()
    if user:
        message = {
            'status_code' : 20003,
            'message' : 'email exists'
        }
        resp = jsonify(message)
        return resp

    user = User.query.filter_by(username=username).first()
    if user:
        message = {
            'status_code' : 20004,
            'message' : 'username exists'
        }
        resp = jsonify(message)
        return resp    

    new_user = User(email=email, username=username, nickname=username, password=password)
    profile = Profile()
    new_user.profile = profile
    db.session.add(new_user)
    db.session.commit()
    message = {
            'status_code' : 10000,
            'message' : 'success',
            'user':{
                'id' : new_user.id, 
                'username' : new_user.username,
                'email': new_user.email,
            }
        }
    resp = jsonify(message)
    resp.mimetype='application/json'
    return resp

@api.route("/account/password_update", methods = ['POST'])
@requires_auth
def password_update():
    current_password = request.values.get('current_password')
    new_password = request.values.get('new_password')
    repeat_password = request.values.get('repeat_password')

    if not current_password or not new_password or not repeat_password:
        message = {
            'status_code' : 20001, 
            'message' : 'args is null',
        }
        resp = jsonify(message)
        resp.mimetype='application/json'
        return resp

    if new_password != repeat_password:
        message = {
            'status_code' : 20002,
            'message' : 'password does not matchrd'
        }
        resp = jsonify(message)
        resp.mimetype='application/json'
        return resp

    auth = request.authorization
    user, authenticated = User.query.authenticate(auth.username, current_password)
    if not authenticated:
        message = {
            'status_code' : 10002,
            'message': 'the password is wrong',
        }
        resp = jsonify(message)
        resp.mimetype='application/json'
        return resp

    user.password = new_password
    db.session.add(user)
    db.session.commit()
    message = {
            'status_code' : 10000,
            'message' : 'success',
        }
    resp = jsonify(message)
    resp.mimetype='application/json'
    return resp


@api.route("/account/contact_update", methods = ['POST'])
@requires_auth
def contact_update():
    phone = request.values.get('phone')
    auth = request.authorization
    user = User.query.filter_by(username=auth.username).first()
    profile = user.profile
    if not profile:
        profile = Profile()
        profile.user = user

    profile.phone = phone
    db.session.add(user)
    db.session.commit()
    message = {
            'status_code' : 10000,
            'message' : 'success',
        }
    resp = jsonify(message)
    resp.mimetype='application/json'
    return resp




# @api.route("/my/travel/create", methods=['POST'])
# @requires_auth
# def my_travel_create():
#     id = request.values.get('id')
#     cruiseprice = Cruiseprice.query.get(id)
#     if not cruiseprice:
#         abort(403)
#     print cruiseprice.id
#     auth = request.authorization
#     user = User.query.filter_by(username=auth.username).first()
#     user.my_cruise_travel = cruiseprice
#     db.session.add(user)
#     db.session.commit()

#     message = {
#             'status_code' : 10000,
#             'message' : 'success',
#         }
#     resp = jsonify(message)
#     resp.mimetype='application/json'
#     return resp

# @api.route("/my/travel", methods=['GET'])
# @requires_auth
# def my_product():
#     auth = request.authorization
#     user = User.query.filter_by(username=auth.username).first()
#     cruiseprice = user.my_cruise_travel
#     product_dict = {}
#     ship_dict = {}
#     city_list = []
    
#     if cruiseprice:
#         product_dict = {
#             'id' : cruiseprice.product.id,
#             'title' : cruiseprice.product.title,
#             'depart_city' : depart_cities.get(cruiseprice.product.depart_city),
#             'cruise' : {
#                     "id" : cruiseprice.product.cruises[0].id if cruiseprice.product.cruises else '',
#                     "name" : cruiseprice.product.cruises[0].ship_name if cruiseprice.product.cruises else '',
#                     "thumb" : cruiseprice.product.cruises[0].thumb() if cruiseprice.product.cruises else ''
#             },
#             'routemap' : cruiseprice.product.get_routemap(),
#             'price' : cruiseprice.product.price,
#             'status' : 1 if cruiseprice.product._status == 2 else 0
#         }
#         routes = [
#             {
#                 'id':route.id,
#                 'name':route.name,
#                 'parent_id':route.parent_id or 0
#             }
#             for route in cruiseprice.product.places if route.type == 'route'
#         ]
#         product_dict['routes'] = routes
#         portcity_ids = json.loads(cruiseprice.product.trips)
#         portcities = [Portcity.query.get(portcity_id) for portcity_id in portcity_ids]
#         details = [
#             {
#                 'id':cruiseportcity.portcity_id,
#                 'name':cruiseportcity.portcity.name,
#                 'thumb':cruiseportcity.portcity.image((240,130)),
#                 'arrive_time': cruiseportcity.arrive_time or '',
#                 'depart_time': cruiseportcity.depart_time or ''
#             }
#             for cruiseportcity in cruiseprice.product.cruiseportcities
#         ]
#         product_dict['details'] = details

#         print '\nproduct',cruiseprice.product.id
#         plans = []
#         plan = cruiseprice
#         print '\n cruiseprice', plan.id
#         prices = {}
#         for price in json.loads(plan.prices):
#             print price.get('amount')
#             if prices.get(price.get('type')):
#                 prices[price.get('type')] = \
#                 int(price.get('amount')) \
#                 if int(prices.get(price.get('type')))> int(price.get('amount')) \
#                 else int(prices.get(price.get('type')))
#             else:
#                 prices[price.get('type')] = int(price.get('amount'))
#             print price.get('type').encode('utf-8'), 'low price', prices[price.get('type')]

#         plans.append({
#                 'id': plan.id,
#                 'depart_date': datetime.datetime.strftime(plan.date,"%Y-%m-%d"),
#                 'prices' : prices,
#                 # 'note' : plan.note,
#                 'note' : "<p>显示的价格是基于标准双人房的单人价格(本目录中最低价格)，包含港务费，不包含服务费、保险费和岸上游等费用</p>\
#                           <p>13周岁以下儿童免船票：13周岁以下儿童与两位全额付费的乘客同住一间家庭舱，可享受船票全免（但需交纳签证费、港务费、服务费用、岸上观光费）</p>\
#                           <p>显示的价格为提前预订价，仅限于有限名额，仅供参考</p>",
#                 'updated': plan.updated, 
#                 'promoted' : plan.promoted,
#                 'status' : plan.status
#             })

#         product_dict['plans'] = plans
        
#         ship_name = cruiseprice.product.cruises[0].ship_name if cruiseprice.product.cruises else ''

#         ship = Ship.query.filter_by(name=ship_name).first()
                

#         ship_dict = {'ship_name':ship.name} if ship else {'ship_name':''}

#         facility_list = []
#         if ship:
#             for facility in ship.facilities:
#                 facility_list.append(
#                     {
#                         'name':facility.name,
#                         'location':facility.location,
#                         'deck_name':facility.deck.name,
#                         'deck_image_url':facility.deck.image
#                     }
#                     )
#         ship_dict['facilities'] = facility_list

#         city_names = [
#             cruiseportcity.portcity.name \
#             for cruiseportcity in cruiseprice.product.cruiseportcities
#         ]

#         city_names = list(set(city_names))

#         if u'航海日' in city_names:
#             city_names.remove(u'航海日')

#         cities = City.query.filter(City.name.in_(city_names)).all()

#         city_list = []
#         for city in cities:
#             city_dict = {
#                 'name':city.name,
#                 'map_url' : city.map 
#             }
#             weather_list = []
#             for weather in city.weathers[:5]:
#                 weather_list.append(
#                     {
#                         'date':str(weather.date),
#                         'bwea':weather.bwea,
#                         'tmin':weather.tmin,
#                         'tmax':weather.tmax
#                     }
#                     )
#             city_dict['weathers'] = weather_list
#             city_list.append(city_dict)

#     message = {
#         'status_code' : 10000,
#         'message' : 'success',
#         'product' : product_dict if product_dict else None,
#         'ship' : ship_dict if ship_dict else None,
#         'cities' : city_list if city_list else None
#     }
#     resp = jsonify(message)
#     resp.mimetype='application/json'
#     return resp
 
# @api.route("/my/travel/destory", methods=['GET'])
# @requires_auth
# def destory_my_product():
#     auth = request.authorization
#     user = User.query.filter_by(username=auth.username).first()
#     user.my_cruise_travel = None
#     # user.my_cruise_travel.remove(cruiseprice)
#     db.session.add(user)
#     db.session.commit()
#     message = {
#         'status_code' : 10000,
#         'message' : 'success',
#     }
#     resp = jsonify(message)
#     resp.mimetype='application/json'
#     return resp

